'use strict';

angular.module('afasApp')
  .controller('CoursesCtrl', ['$scope', '$rootScope', '$modal', 'Services', '$state', '$filter', function ($scope, $rootScope, $modal, Services, $state, $filter) {

    console.log($filter);

    $scope.courses       = [];
    $scope.coursetypes   = [];
    $scope.subjects      = [];
    $scope.subject       = {
      CourseLevel: {},
      LookupScores: [],
      RangeScore: {}
    };
    $scope.terms           = [];
    $scope.courseNew       = {};
    $scope.errors          = {};
    $scope.currentCourse   = {};
    $scope.psForm          = false;
    $scope.psSubjectNew    = false;
    $scope.psSubjectUpdate = false;
    $scope.filterTable     = {};

    $scope.params = {
      'keyword': $scope.searchText,
      'include': 'all'
    };

    // COURSE TYPES
    Services.getItems($scope.COURSETYPE_URL)
    .then(function(results){
      $scope.coursetypes = results.data;
      $scope.params.course_type = $scope.coursetypes[0].Id;
    });

    Array.prototype.move = function (from, to) {
      this.splice(to, 0, this.splice(from, 1)[0]);
    };

    // PAGINATION
    $scope.pagesize = 50; // based on how many course levels are there in IALF.

    $scope.pagination = {
      current: 1
    };

    $scope.pageChanged = function(newPage) {
      getResultsPage(newPage);
    };

    function getResultsPage(pageNumber) {
      var data = $scope.params;
      data.pagesize = $scope.pagesize;
      data.page = (pageNumber - 1);
      $scope.pagination.current = pageNumber;
      data.include = 'subjects';
      Services.getItems('course_levels', data)
      .then(function( results ) {
        var pagingData = angular.fromJson(results.headers['x-pagination']);
        $scope.totalItems = pagingData.TotalCount;
        $scope.courses = results.data;
        $scope.courses = _.filter($scope.courses, function(obj) {
          return obj.CourseType.Id === $scope.params.course_type;
        });
      });
    }
    getResultsPage(1);

    // SUBJECT METHODS
    $scope.CreateNewSubject = function (course) {

      $scope.subject.CourseLevel.Id = course;

      $scope.psSubjectNew = true;
    };

    $scope.loadSubjects = function(course){
      $scope.psForm = true;
      $scope.currentCourse = course;
      $scope.subjects = course.Subjects;
    };

    $scope.saveSubject = function(){
      $scope.errors = {};
      if ($scope.subject.ScoreType === 1) {
        delete $scope.subject.RangeScore;
        angular.forEach($scope.subject.LookupScores, function(value, key){
          value.Order = key;
        });
      } else {
        $scope.subject.RangeScore.IsIntegerOnly = true;
        delete $scope.subject.LookupScores;
      }
      Services.add('subjects', $scope.subject)
      .then(function(results){
        $scope.subject = {
          CourseLevel: {},
          LookupScores: [],
          RangeScore: {}
        };
        $scope.psSubjectNew = false;
        $scope.subjects.push(results.data);
      }, function(results){
        if (results.status == 400) {
          $scope.errors = results.data;
          if ($scope.subject.ScoreType === 0) {
            $scope.subject.LookupScores = [];
          } else {
            $scope.subject.RangeScore = {};
          }
        }
      });
    };

    $scope.loadCourses = function(Id) {
      $scope.params.course_type = Id;
      getResultsPage(1);
    };

    $scope.addLookupScore = function(){
      var newScore = {
        Name: '',
        Value: ''
      };
      $scope.subject.LookupScores.push(newScore);
    };

    $scope.editSubject = function(subject){
      $scope.subject = subject;
      $scope.subject.CourseLevel = {
        Id: $scope.currentCourse.Id
      };
      $scope.psSubjectUpdate = true;
    };

    $scope.updateSubject = function(){
      $scope.errors = {};
      if ($scope.subject.ScoreType === 1) {
        delete $scope.subject.RangeScore;
        angular.forEach($scope.subject.LookupScores, function(value, key){
          value.Order = key;
        });
      } else {
        $scope.subject.RangeScore.IsIntegerOnly = true;
        delete $scope.subject.LookupScores;
      }

      Services.update('subjects', $scope.subject, $scope.subject.Id)
      .then(function(results){
        $scope.subject = {
          CourseLevel: {},
          LookupScores: [],
          RangeScore: {}
        };
        $scope.psSubjectUpdate = false;
      }, function(results){
        if (results.status == 400) {
          $scope.errors = results.data;
          if ($scope.subject.ScoreType === 0) {
            $scope.subject.LookupScores = [];
          } else {
            $scope.subject.RangeScore = {};
          }
        }
      });
    };

    $scope.remove = function(index) {
      $scope.subject.LookupScores.splice(index, 1);
    };

    $scope.moveUp = function(index) {
      $scope.subject.LookupScores.move(index,(index-1));
    };

    $scope.moveDown = function(index) {
      $scope.subject.LookupScores.move(index,(index+1));
    };

    $scope.addCourse = function () {
      // console.log($scope.courseNew);
      $scope.errors = {};
      Services.add('course_levels', $scope.courseNew)
      .then(function(){
        $scope.courseNew = {};
        $state.go( '^.list' );
      }, function(results){
        if (results.status == 400) {
          $scope.errors = results.data;
        }
      });
    };

    $scope.deleteCourse = function (course) {
      Services.delete('course_levels', course)
      .then(function(){
        loadRemoteData();
      });
    };

    $scope.callTerm = function () {

      var paramCourse = {
        'course_type': $scope.filterTable.CourseType.Id,
        'order_by': 'year',
        'order_type': 'desc',
        'getall': true
      };

      Services.getItems('terms', paramCourse)
      .then(function( results ) {
        $scope.terms = results.data;
      });
    };
  }])
  .controller('CourseCtrl', ['$scope', 'Services', '$state', '$stateParams', '$filter', function ($scope, Services, $state, $stateParams, $filter) {

    $scope.currentCourse = {};
    $scope.currentID = $stateParams.id;
    // $scope.currentCourse = Courses.getCourse($stateParams.id);

    $scope.currencies = [];
    $scope.coursetypes = [];

    Services.getItems('currencies')
    .then(function(results){
      $scope.currencies = results;
    });

    Services.getItems('course_types')
    .then(function(results){
      $scope.coursetypes = results;
    });

    // Services.getItem('courses', $scope.currentID)
    // .then(function(results){
    //   $scope.currentCourse = results;
    // });


    $scope.calculate = function (valueCur, currency) {
      if (currency) {
        $scope.conversionResult = valueCur * $scope.currencies[currency].RupiahRate;
        $scope.conversionResult = $filter('currency')($scope.conversionResult, 'Rp ');
      }
    };

    $scope.updateCourse = function () {
      console.log($scope.currentCourse);
      console.log($scope.currentID);
      Services.update('courses', $scope.currentCourse, $scope.currentID)
      .then(function(results){
        console.log(results);
        // $state.go( '^.show', {id: $scope.currentID} );
        $state.go( '^.list');
      });
    };
  }])
  .controller('CourseInstallmentCtrl', ['$scope', 'Services', 'Courses', '$state', '$stateParams', '$filter', 'Currencies', 'CourseTypes', 'Terms', function ($scope, Services, Courses, $state, $stateParams, $filter, Currencies, CourseTypes, Terms) {

    console.log($filter);

    $scope.currentCourse = {};
    $scope.currentID = $stateParams.id;
    $scope.coursetypes = CourseTypes.getCourseTypes();
    $scope.currencies = Currencies.getCurrencies();
    $scope.terms = Terms.getTerms();
    $scope.currentCourse =Courses.getCourse($stateParams.id);
    $scope.installmentNew = {};
    if (!$scope.currentCourse.Installments) {
      $scope.currentCourse.Installments = [];
    }

    $scope.updateCourse = function () {
      Courses.updateCourse($scope.currentCourse, $scope.currentID);
      $scope.installmentNew = {};
      // $state.go( 'courses.show', {id: $scope.currentID} );
    };

    $scope.addInstallment = function () {
      // console.log($scope.courseNew);
      $scope.currentCourse.Installments.push($scope.installmentNew);
      $scope.updateCourse();
    };

    $scope.deleteInstallment = function (index) {
      $scope.currentCourse.Installments.splice(index, 1);
      $scope.updateCourse();
    };
  }])
  .controller('CourseFeeCtrl', ['$scope', 'Services', '$state', '$stateParams', '$filter', '_', function ($scope, Services, $state, $stateParams, $filter, _) {

    console.log($filter);

    $scope.fees = [];
    $scope.courses = [];
    $scope.currencies = [];

    Services.getItems('currencies')
    .then(function(results){
      $scope.currencies = results.data;
    });

    function loadFees(){
      $scope.fees = [];
      $scope.courses = [];
      Services.getItems('course_fees', {'active': true, 'getall': true})
      .then(function(results){
        var fees = results.data;
        angular.forEach(fees, function(value, key){
          $scope.fees[value.Course.Id] = value;
        });

        Services.getItems('courses', {'include': 'all', 'getall': true})
        .then(function(results){
          $scope.courses = results.data;
          $scope.courses = _.groupBy($scope.courses, function(item){ return item.CourseLevel.Name; });
        });
      });
    };

    loadFees();


    $scope.isUsing = function(course, type){
      var results = _.where(course, {TeacherType: type});
      // console.log(results);
      return results.length > 0;
    };

    $scope.courseId = function(course, type){
      var result = _.findWhere(course, {TeacherType: type});
      if (result.Id) {
        if (!$scope.fees[result.Id]) {
          $scope.fees[result.Id] = {};
        };
        if ($scope.fees[result.Id].Course) {
          $scope.fees[result.Id].Course.Id = result.Id;
        } else {
          $scope.fees[result.Id].Course = {
            Id: result.Id
          };
        };
      };
      // console.log(results);
      return result.Id;
    };

    $scope.save = function(){
      $scope.fees = _.filter($scope.fees, function(item){ return item.hasOwnProperty('Fee'); });
      console.log($scope.fees);
      Services.add('course_fees', $scope.fees)
      .then(function(results){
        console.log(results);

        loadFees();
      }, function(results){
        if (results.status == 400) {
          $scope.errors = results.data;
        }
      });
    };
  }]);